import os, sys
import StringIO

anoxdataPath = "C:\\Games\\Anachronox\\anoxdata"
mapsPath = os.path.join(anoxdataPath, "MAPS")

if len(sys.path[0]):
    # Executed from the command line.
    outPath = sys.path[0]
else:
    # Executed from some windows thing.
    outPath = os.getcwd()

# Make the output sub-directory.
outPath = os.path.join("entities-parse")
try:
    os.mkdir(outPath)
except OSError:
    pass

from anoxtools import BSP

for filename in os.listdir(mapsPath):
    if not filename.endswith(".bsp"):
        continue
    f = open(os.path.join(mapsPath, filename), 'rb')
    try:
        reader = BSP.BSPReader(f, "blah")
        reader.ParseEntities(f)
    finally:
        f.close()

    s = ""
    outFilename = None

    if True:
        outFilename = filename[:-4] +".html"

        s += "<html>"
        s += "<body>"
        s += "<h1>File: %s</h1>" % filename
        for entry in reader.entryList:
            s += entry.HTML()
        s += "</body>"
        s += "</html>"

    if False:
        skipClasses = {
            "light": None,
        }
        skipKeys = {
            "_color": None,
            "_lightmin": None,
            "_sun_ambient": None,
            "_sun_angle": None,
            "_sun_color": None,
            "_sun_light": None,
            "_sun2_angle": None,
            "_sun2_light": None,
            "_sun2_color": None,
            "alpha": None,
            "alphaflags": None,
            "angle": None,
            "angles": None,
            "attenuation": None,
            "battlegroupname": None,
            "classname": None,
            "count": None,
            "default_ambient": None,
            "defualt_ambient": None,
            "Default_anim": None,
            "default_anim": None,
            "defualt_anim": None,
            "default_walk": None,
            "distance": None,
            "dlltexture01": None,
            "dlltexture02": None,
            "dlltexture03": None,
            "fog": None,
            "force_2d": None,
            "gridsize": None,
            "light": None,
            "lighting": None,
            "lip": None,
            "lowest": None,
            "map": None,
            "max": None,
            "maxs": None,
            "maxsx": None,
            "maxsy": None,
            "maxsz": None,
            "message": None,        # text
            "min": None,
            "mins": None,
            "minsx": None,
            "minsy": None,
            "minsz": None,
            "model": None,
            "ndscale": None,
            "newscaling": None,
            "noise": None,
            "noise2": None,
            "np": None,
            "np_1": None,
            "np_2": None,
            "np_3": None,
            "npsimple": None,
            "offset": None,
            "origin": None,
            "particleflags": None,
            "path_anim": None,
            "pathanim": None,
            "pathtarget": None,
            "spawncondition": None,     # ape expression
            "spawnconditon": None,
            "random": None,
            "removed_sequence": None,
            "rgb": None,
            "scale": None,
            "seqence": None,
            "sequence": None,
            "sky": None,
            "skyaxis": None,
            "skyrotate": None,
            "sound": None,
            "spawnflags": None,
            "speed": None,
            "sun_ambient": None,
            "sun_diffuse": None,
            "style": None,
            "target": None,
            "targetname": None,
            "targtename": None,
            "team": None,
            "volume": None,
            "wait": None,
            "wsequence": None,
        }
        for entry in reader.entryList:
            if skipClasses.has_key(entry.classname):
                continue
            cnt = len(entry.__dict__)
            for k, v in entry.__dict__.iteritems():
                if skipKeys.has_key(k):
                    cnt -= 1
                else:
                    if k in ("command", "touchconsole"):
                        bool = False
                        for s2 in ("fov", "gl_fog", "battlestart", "target "):
                            bool = v.startswith(s2)
                            if bool:
                                break
                        if bool:
                            cnt -= 1
                            continue
                        
                    try:
                        int(v)
                        cnt -= 1
                        continue
                    except ValueError:
                        pass

                    try:
                        float(v)
                        cnt -= 1
                        continue
                    except ValueError:
                        pass
            if cnt:
                s += entry.String(skipKeys)

    if False:
        skips = {
            "light": None,
        }
        matches = {}
        for entry in reader.entryList:
            if skips.has_key(entry.classname):
                continue
            for k, v in entry.__dict__.iteritems():
                idx = v.find(":")
                if idx == -1:
                    continue
                prefix = v[:idx]
                try:
                    int(prefix)
                except ValueError:
                    continue
                suffix = v[idx+1:]
                try:
                    int(suffix)
                except ValueError:
                    continue
                if matches.has_key(k):
                    matches[k][entry.classname] = None
                else:
                    matches[k] = { entry.classname: None }                        
            s += str(entry)                

        s2 = ""
        for k, d in matches.iteritems():
            s2 += "%s: %s\n" % (k, str(d))
        s = s2 + s

    if False:
        d = {}
        for entry in reader.entryList:
            if entry.classname == "light":
                for k, v in entry.__dict__.iteritems():
                    if k != "classname":
                        if d.has_key(k):
                            d[k] += 1
                        else:
                            d[k] = 1

        l = d.items()
        l.sort()

        for k, v in l:
            s += "%s: %s\n" % (k, v)

    if False:
        d = {}
        for entry in reader.entryList:
            if d.has_key(entry.classname):
                d[entry.classname] += 1
            else:
                d[entry.classname] = 1
        l = d.items()
        l.sort()

        for k, v in l:
            s += "%s: %s\n" % (k, v)

    if outFilename is None:
        outFilename = filename[:-4] +".ent"

    if len(s):
        f = open(os.path.join(outPath, outFilename), "w")
        try:
            f.write(s)
        finally:
            f.close()        
        